package com.lagou.module3_6;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author wsl
 * @date 2021/7/21 23:16
 * @project_name javase
 */
public class StudentMapTest {

    public static void main(String[] args) {

        //1.定义Map集合，用Student对象作为key，用字符串(此表示表示学生的住址)作为value
        Map<Student,String> m1 = new HashMap<>();
        System.out.println("m1= "+m1);//{}

        //向集合中添加元素
        m1.put(new Student("张三",18),"上海！");
        m1.put(new Student("李四",30),"北京！");
        m1.put(new Student("王五",25),"广州！");

        SetMethod1(m1);
        SetMethod2(m1);
    }

    private static void SetMethod2(Map<Student, String> m1) {
        //方式一：
        //调用Map集合方法entrySet方法，获取Map集合中的所有键值对，并组成Set视图
        Set<Map.Entry<Student, String>> studentSet1 = m1.entrySet();
        //用Iterator迭代取出Key:
        Iterator<Map.Entry<Student, String>> studentIt = studentSet1.iterator();
        while (studentIt.hasNext()){//判断是否有key存在
            Map.Entry<Student, String> stu1 = studentIt.next();
            Student studentKey = stu1.getKey();
            String value = stu1.getValue();
            System.out.println("\t"+studentKey+"的地址是："+value);
        }
        System.out.println("---------------------------------------------------------");
        //方式二：
        //使用for...each循环取出key:
        for(Map.Entry<Student, String> stu2:studentSet1){
            Student studentKey = stu2.getKey();
            String value = stu2.getValue();
            System.out.println("\t"+studentKey+"的地址是："+value);
        }
        System.out.println("---------------------------------------------------------");

    }

    private static void SetMethod1(Map<Student, String> m1) {
        System.out.println("---------------------------------------------------------");
         //方式三：
         //调用Map集合方法KeySet方法，获取Map集合中的所有键值对，并组成Set视图
        Set<Student> studentSet2 = m1.keySet();
        //用Iterator迭代取出key:
        Iterator<Student> studentIt = studentSet2.iterator();
        while (studentIt.hasNext()){
            Student studentKey = studentIt.next();
            String value = m1.get(studentKey);
            System.out.println("\t"+studentKey+"的地址是："+value);
        }
        System.out.println("---------------------------------------------------------");
        //方式四：
        //使用for...each循环取出key:
        for (Student stu3:studentSet2){
            Student studentKey = stu3;
            String value = m1.get(studentKey);
            System.out.println("\t"+studentKey+"的地址是："+value);
        }
        System.out.println("---------------------------------------------------------");
    }
}
